package com.guodefu.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.guodefu.demo.domain.DictionaryDO;
import com.guodefu.demo.service.DictionaryService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 应用启动后，查询所有的 Dictionary 对象，进行缓存
 */
@Slf4j
@Component
public class DictionaryCacheLoader implements CommandLineRunner {

    private final DictionaryService dictionaryService;

    private final ObjectMapper objectMapper;

    public DictionaryCacheLoader(DictionaryService dictionaryService, ObjectMapper objectMapper) {
        this.dictionaryService = dictionaryService;
        this.objectMapper = objectMapper;
    }

    @SneakyThrows
    @Override
    public void run(String... args) {
        List<DictionaryDO> allDictionaries = dictionaryService.list();
        for (DictionaryDO dict : allDictionaries) {
            dictionaryService.cacheByTypeAndCode(dict);
            dictionaryService.cacheById(dict);
            log.info("正在缓存对象：{}", objectMapper.writeValueAsString(dict));
        }
    }
}

